package cn.edu.ctbu.eol.teacher.aspect;

import cn.edu.ctbu.eol.teacher.common.CustomException;
import cn.edu.ctbu.eol.teacher.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class LoginCheckAspect {

    @Autowired
    private JwtUtil jwtUtil;

    @Pointcut("execution(* cn.edu.ctbu.eol.teacher.controller.*.*(..)) && " +
            "!execution(* cn.edu.ctbu.eol.teacher.controller.TeacherController.login(..))")
    public void loginCheck() {
    }

    @Before("loginCheck()")
    public void before() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || authHeader.isEmpty()) {
            throw new CustomException("未登录");
        }

        if (!authHeader.startsWith("Bearer ")) {
            throw new CustomException("无效的token格式");
        }

        String token = authHeader.substring(7);

        if (jwtUtil.isTokenExpired(token)) {
            throw new CustomException("登录已过期，请重新登录");
        }
    }
} 